import markdown
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render, redirect, get_object_or_404

# Create your views here.
from communications.forms import PlatePostForm, CommentForm
from users.models import User
from .models import PlatePost, Plate, PlateCategory, PlateComment, PostColumn, PostLike
from communications import creations


def information_view(request, category_id):
    # print(Plate.objects.all().count())
    # if (Plate.objects.all().count()) == 0:
    #     creations.create_plate()
    # if (PlateCategory.objects.all().count()) == 0:
    #     creations.create_category()
    # if (PostColumn.objects.all().count()) == 0:
    #     creations.create_column()

    search = request.GET.get('search')
    order = request.GET.get('order')

    posts_fav = PlatePost.objects.all().order_by('-no_visitor')[:5]

    # 搜索
    if search:
        if order == 'no_visitor':
            # Q对象
            posts = PlatePost.objects.filter(

                (Q(content__icontains=search)|Q(title__icontains=search))

            ).order_by('-no_visitor')
        else:
            posts = PlatePost.objects.filter(

                (Q(content__icontains=search) | Q(title__icontains=search))
            )
    else:
        # search置空
        search = ''
        if order == 'no_visitor':
            # Q对象
            posts = PlatePost.objects.filter(
                Q(category=category_id)
            ).order_by('-no_visitor')
        else:
            posts = PlatePost.objects.filter(
                Q(category=category_id)
            )

        # 根据GET请求中查询条件
        # 返回不同排序的对象数组
        # if request.GET.get('order') == 'no_visitor':
        #     information_posts = PlatePost.objects.all().filter(category=1).order_by('-no_visitor')
        #     order = 'no_visitor'
        # else:
        #     information_posts = PlatePost.objects.all().filter(category=1)
        #     order = 'normal'
        # # 取出所有文章
        # information_posts = PlatePost.objects.all().filter(category=1)
        # 取出文章评论

    # 每页显示 5 篇文章
    paginator = Paginator(posts, 5)
    # 获取 url 中的页码
    page = request.GET.get('page')
    # 将导航对象相应的页码内容返回给 articles
    posts = paginator.get_page(page)

    category_class_id = category_id

    context = {'posts': posts, 'order': order, 'search': search, 'category_class_id': category_class_id,
               'posts_fav': posts_fav}
    return render(request, 'communications/information.html', context)


def post_detail_view(request, id):
    # PostLikeCount = PostLike.objects.filter(post=id, author=request.user).count()
    # if PostLikeCount == 1:
    #     like_status = 1
    # else:
    #     like_status = 0
    # 取出相应的文章
    post = PlatePost.objects.get(id=id)
    # 浏览量 +1
    post.no_visitor += 1

    post.save(update_fields=['no_visitor'])
    # 将markdown语法渲染成html样式
    post.content = markdown.markdown(post.content,
                                     extensions=[
                                         # 包含 缩写、表格等常用扩展
                                         'markdown.extensions.extra',
                                         # 语法高亮扩展
                                         'markdown.extensions.codehilite',
                                     ])
    # 取出文章评论
    post_comments = PlateComment.objects.filter(post=id)
    # 需要传递给模板的对象
    context = {'post': post, 'post_comments': post_comments}
    return render(request, 'communications/post_detail.html', context)


@login_required(login_url='users:login')
def post_no_like_add_view(request, id):
    post = PlatePost.objects.get(id=id)
    if request.user in post.likeUser.all():
        post.likeUser.remove(request.user)
        post.save()
    else:
        post.likeUser.add(request.user)
        post.save()

    post.no_like = post.likeUser.count()

    post.save(update_fields=['no_like'])
    # print(context)
    return redirect(post)


# 删除文章视图
def post_delete_view(request, id):
    # 取出相应的文章
    post = PlatePost.objects.get(id=id)
    post.delete()
    return redirect("communications:postCreate")


@login_required(login_url='users:login')
def post_create_view(request):
    # 判断用户是否提交数据
    if request.method == "POST":
        # 将提交的数据赋值到表单实例中
        plate_post_form = PlatePostForm(data=request.POST)
        # 判断提交的数据是否满足模型的要求
        # print(plate_post_form)
        if plate_post_form.is_valid():
            # 保存数据，但暂时不提交到数据库中
            new_post = plate_post_form.save(commit=False)
            # 指定数据库中 id=3 的用户为作者
            # new_post.author = User.objects.get(id=3)
            # 指定数据库中的当前登录用户为作者
            new_post.author = request.user
            # 新增的代码
            if request.POST['column'] != 'none':
                new_post.column = PostColumn.objects.get(id=request.POST['column'])
            # 将新文章保存到数据库中

            new_post.save()
            # 保存tags的多对多关系
            plate_post_form.save_m2m()
            # 完成后返回到文章列表
            return redirect(new_post)
        # 如果数据不合法，返回错误信息
        else:
            return HttpResponse("表单内容有误，请重新填写。")
    # 如果用户请求获取数据
    else:
        # 创建表单类实例
        plate_post_form = PlatePostForm()
        # 栏目
        columns = PostColumn.objects.all()

        # 赋值上下文
        context = {'plate_post_form': plate_post_form, 'columns': columns}
        # 返回模板
        return render(request, 'communications/post_create.html', context)


@login_required(login_url='users:login')
def post_update_view(request, id):
    # 获取要修改的文章对象
    post = PlatePost.objects.get(id=id)
    if request.method == "POST":
        # 将提交的数据赋值到表单实例中
        plate_post_form = PlatePostForm(data=request.POST)
        # 判断提交的数据是否满足模型的要求
        if plate_post_form.is_valid():
            # 保存新泻入的数据并保存
            post.title = request.POST['title']
            post.category = PlateCategory.objects.get(id=request.POST['category'])
            post.column = PostColumn.objects.get(id=request.POST['column'])
            post.content = request.POST['content']
            post.tags = request.POST['tags']
            # 将新文章保存到数据库中

            post.save()

            return redirect(post)
        else:
            return HttpResponse("表单内容有误，请重新填写。")
    else:
        # 创建表单类实例
        plate_post_form = PlatePostForm()
        # 栏目
        columns = PostColumn.objects.all()

        # 赋值上下文
        context = {'plate_post_form': plate_post_form, 'columns': columns}
        # 返回模板
        return render(request, 'communications/post_update.html', context)


@login_required(login_url='users:login')
def post_comment_view(request, post_id):
    post = get_object_or_404(PlatePost, id=post_id)

    # 处理post请求
    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        # print(comment_form)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.post = post
            new_comment.author = request.user
            new_comment.save()
            # 取出文章评论个数
            no_post_comments = PlateComment.objects.filter(post=post_id).count()
            post.no_comment = no_post_comments
            post.save(update_fields=['no_comment'])
            return redirect(post)
        else:
            return HttpResponse("表单内容有误，请重新填写。")
    else:
        return HttpResponse("发表评论仅接受POST请求。")
